package sample.tangocho.dataaccess;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sample.tangocho.model.Card;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CardDaoImpl extends SQLiteDao implements CardDao {

	public CardDaoImpl(Context context) {
		super(context);
	}

	@Override
	public void insertCard(long tangochoId, String frontText, String backText) {
		
		ContentValues values = new ContentValues();
		values.put("tangocho_id", tangochoId);
		values.put("front_text", frontText);
		values.put("back_text", backText);
		values.put("last_updated", new Date().getTime());
		getTangochoSQLiteOpenHelper().getWritableDatabase().insert("card",
				null, values);

	}

	@Override
	public List<Card> selectCardList(int tangochoId) {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();

		List<Card> cardList = new ArrayList<Card>();

		Cursor cursor = db.query("card", null, "tangocho_id = ?", new String[]{String.valueOf(tangochoId)}, null, null, null);

		if (cursor.moveToFirst()) {
			do {
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				String frontText = cursor.getString(cursor.getColumnIndex("front_text"));
				String backText = cursor.getString(cursor.getColumnIndex("back_text"));
				long lastUpdated = cursor.getLong(cursor.getColumnIndex("last_updated"));
				
				Card card = new Card();
				card.setId(id);
				card.setFrontText(frontText);
				card.setBackText(backText);
				card.setLastUpdated(lastUpdated);
				
				cardList.add(card);
			} while(cursor.moveToNext());
		}
		
		return cardList;
	}

	@Override
	public void deleteCard(int cardId) {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();
		db.delete("card", "_id = ?", new String[]{String.valueOf(cardId)});
	}

	@Override
	public int deleteCardByTangochoId(int tangochoId) {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();
		return db.delete("card", "tangocho_id = ?", new String[]{String.valueOf(tangochoId)});
	}

	@Override
	public void updateCard(Card card) {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();
		ContentValues contentValues = new ContentValues();
		contentValues.put("front_text", card.getFrontText());
		contentValues.put("back_text", card.getBackText());
		contentValues.put("last_updated", new Date().getTime());
		db.update("card", contentValues, "_id = ?", new String[]{String.valueOf(card.getId())});
	}

}
